import { URL_BUY_EQUITY, URL_CAPITAL_EQUITY, URL_KLINE_DATA, URL_TOKEN_DATA } from "@/comm/api";
import { toChartData } from "@/comm/format";
import { get } from "@/comm/request";
import { sortList } from "@/comm/tooler";
import { initChartConfig } from "@/components/chart/config";
import { customStyle } from "@/components/chart/customStyle";
import { noneCustomStyle } from "@/components/chart/noneCustom";
import { formatBigNumber, formatTimestamp } from "@/comm/format";
import { getNearData, getTimer, getFormatTime } from "@/components/chart/core/tooler";
import { ref, reactive } from "vue";
import { useKline } from "@/stores/kline";

const { init, dispose, registerOverlay, registerFigure, getFigureClass, getSupportedFigures, registerIndicator } = (window as any)["klinecharts"];
export const useChart = function () {
    const usekline = useKline();
    const loading = ref(false);
    const curItem = ref<any>(null);
    const move = ref<any>();
    const moreList = ref();
    const KLineType = ref("candle_solid");
    const tables = reactive({
        bs: {
            x: -1200,
            y: 0
        },
        link: {
            right: ""
        },
        more: {
            x: -1200,
            y: 0
        }
    });
    let chart: any;
    let token = "";
    let interval = "";
    let klineDataList: any[] = [];
    let allTime: any = {}; //所有包含交易的时间段
    async function initLitterChaet($id: string, $token: string, $interval: string) {
        // console.log('初始化chart===========>')
        if (chart) {
            chart.removeIndicator();
            dispose(chart);
        }
        token = $token;
        interval = $interval;
        // initChartConfig();
        chart = init($id);
        chart.setStyles(noneCustomStyle);
        chart.setStyles({
            candle: {
                type: "area"
            }
        });
        await loadOnLine();
    }
    //仅有ID初始化
    async function initDataChat($id: string) {
        if (chart) {
            chart.removeIndicator();
            dispose(chart);
        }
        initChartConfig();
        chart = init($id);
        chart.setStyles(customStyle);
        // chart.setPriceVolumePrecision(usekline.curCoin.priceDisplayDp, usekline.curCoin.priceDisplayDp);
        // chart.setPriceVolumePrecision(3, 3);
        chart.setStyles({
            candle: {
                type: KLineType.value
            }
        });
        return chart;
    }
    function setChartData(data: any[]) {
        chart.applyNewData(data);
    }
    function setZoomAt(timestamp: number) {
        // console.log('设置图表缩放！！！！！！！！！！！！！！！！！！', timestamp)
        chart.zoomAtTimestamp(1.5, timestamp, 900);

    }
    //点击底部小图标覆盖物事件
    function clickEvent(e: any, list: any[], isPress: boolean) {
        isPress = true;
        console.log("点击K线覆盖物事件============》", list);
        if (list) {
            if (list.length == 1) {
                if (isPress) {
                    tables.bs.x = e.x;
                    tables.bs.y = e.y;
                } else {
                    tables.bs.x = -1200;
                }
                curItem.value = list[0].origin;
            } else {
                moreList.value = list;
                if (isPress) {
                    tables.more.x = e.x;
                    tables.more.y = e.y;
                } else {
                    tables.more.x = -1200;
                }
            }
        }
    }
    //hook内请求初始化
    async function initChart($id: string, $token: string, $interval: string, onLine: boolean) {
        // console.log('初始化chart===========>')
        if (chart) {
            chart.removeIndicator();
            dispose(chart);
        }
        token = $token;
        interval = $interval;
        initChartConfig();
        chart = init($id);
        chart.setStyles(customStyle);
        // chart.setPriceVolumePrecision(usekline.curCoin.priceDisplayDp, usekline.curCoin.priceDisplayDp);
        // chart.setPriceVolumePrecision(11, 3);
        chart.setStyles({
            candle: {
                type: KLineType.value
            }
        });
        loading.value = true;
        if (onLine) {
            await loadOnLine();
        } else {
            await loadData();
        }
        setTimeout(() => {
            loading.value = false;
        }, 120);

        // let list = chart.getDataList();
        // let {outAry, inAry} = await getOutInData(list);
    }
    async function getOutInData(list: any[]) {
        console.log(token, interval, "interval --- token");
        // let list = chart.getDataList();
        let res1: any = await get(URL_CAPITAL_EQUITY.replace("@", token), { type: interval, startTime: list[0].timestamp });
        let outAry = res1.data;
        let res2: any = await get(URL_BUY_EQUITY.replace("@", token), { type: interval, startTime: list[0].timestamp });
        let inAry = res2.data;
        console.log(list, outAry, inAry);
        return { outAry, inAry };
    }
    //设置K线精度
    function flitterVolumePrecision(klist: any[]) {
        if (klist.length == 0) return;
        let minPrecision = Number(klist[0].close);
        //查找出最小的精度位
        for (let i = 0; i < klist.length; i++) {
            // 可能包含科学计数法所以在这里转换数字
            const value = Number(klist[i].close + "");
            if (value < minPrecision) {
                minPrecision = value;
            }
        }
        const countZeros = (num: number) => {
            const sciNotation = num.toExponential();
            const match = sciNotation.match(/e\+?(-?\d+)/i);
            const exponent = match ? parseInt(match[1]) : 0;
            return Math.abs(exponent);
        };
        const precision = countZeros(minPrecision);
        //如果小于3位就给予默认3位
        if (precision < 3) {
            chart.setPriceVolumePrecision(3, 3);
        } else if (precision > 3 && precision < 6) {
            chart.setPriceVolumePrecision(precision + 3, 3);
        } else {
            //如果大于3位就给予最小精度位
            chart.setPriceVolumePrecision(precision, 3);
        }
    }
    //获取图标K线数据
    function getKlineData() {
        return klineDataList;
    }
    //添加内置K线指标
    function appendIndicator(val: any, isStack: boolean) {
        chart.createIndicator(val, isStack);
    }
    //设置K线类型
    function changeChartStyle(isArea: boolean) {
        console.log("###########切换K线类型", isArea);
        chart.setStyles({
            candle: {
                type: isArea ? "area" : "candle_solid"
            }
        });
    }
    /* 
    添加K线轴覆盖物
    过滤出K线中有H线交易的数据  
    并且把每天交易usd最高的那天数据作为addMark
    然后如果每天的数据是大于1条的在addEvent的action就是more
    点击的时候返回当天所有的交易数据显示在K线中
    K线为D时，过滤出K线每天中对应的H线数据 提取出usd最高的那条数据 其余数据在addEvent中more显示
    K线为H时 过滤出K线每小时中对应的H线数据 提取出usd最高的那条数据 其余数据在addEvent中more显示
    */
    function maxUsdDay(klist: any[], hlist: any[], type: string) {
        const timeType = (time: string) => {
            if (time == "D") {
                return "yyyy-MM-dd";
            }
            if (time == "H") {
                return "yyyy-MM-dd hh";
            }
            return "yyyy-MM-dd hh:mm";
        };
        // console.log('K线类型', timeType(type))
        chart.removeIndicator();
        const maxUsd = []; //最高USD的交易段
        allTime = [];
        let all: { [key: string]: any } = {}; //所有包含交易的时间段
        for (let i in klist) {
            let hasDealTime = []; //有交易的时间段
            for (let j in hlist) {
                // console.log(`K 时间：${getFormatTime(klist[i].timestamp, timeType(type))}  H 时间：${getFormatTime(hlist[j].timestamp, timeType(type))}`)
                if (getFormatTime(klist[i].timestamp, timeType(type)) == getFormatTime(hlist[j].timestamp, timeType(type))) {
                    hasDealTime.push({
                        ...klist[i],
                        usd: hlist[j].usd,
                        origin: hlist[j],
                        dtimestamp: hlist[j].timestamp
                    });
                }
            }
            //K线当天有H线数据
            if (hasDealTime.length > 0) {
                // console.log('当天数据=======================》', hasday)
                //查找usd最大值
                hasDealTime.sort((a: any, b: any) => {
                    return b.usd - a.usd;
                });
                maxUsd.push(hasDealTime[0]); //最高USD天数数组

                all[hasDealTime[0].timestamp] = hasDealTime; //将时间段存入对象中
            }
        }

        if (maxUsd.length > 0) {
            allTime = all;
            maxUsd.forEach(item => {
                addMark(item);
            });
        }
    }
    //添加K线覆盖物
    function addMark(val: any) {
        let up = true;
        let title = "";
        let act = "in";

        //转移
        if (val.origin.method == "transfer") {
            //提现
            if (val.origin.action == "withdraw") {
                title = "withdraw";
                act = "out";
                up = true;
            }
            //充值
            if (val.origin.action == "deposit") {
                title = "deposit";
                act = "out";
                up = false;
            }
            //普通转账
            if (val.origin.action == "transfer") {
                title = "transfer";
                act = "out";
                up = false;
            }
        }
        //交易
        if (val.origin.method == "swap") {
            //买
            if (val.origin.action == "buy") {
                title = "buy";
                act = "in";
                up = true;
            }
            //卖
            if (val.origin.action == "sell") {
                title = "sell";
                act = "out";
                up = false;
            }
            //普通交易
            if (val.origin.action == "swap") {
                title = "sell";
                act = "out";
                up = false;
            }
        }

        //买 in
        //卖 out
        let aid = chart.createOverlay({
            name: "action",
            extendData: {
                title: title,
                sub: ``,
                up: up,
                data: val,
                origin: val.origin
            },
            points: [
                {
                    timestamp: val.timestamp,
                    value: val.close
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e,val);
                let extendData = e.overlay.extendData;
                let list = allTime[val.timestamp];
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent && clickEvent(e, list, false);
                } else {
                    extendData.press = true;
                    clickEvent && clickEvent(e, list, true);
                }
                // chart.removeOverlay(fg)
            },
            onMouseEnter: (e: any) => {
                // console.log(e, "enter")
            },
            onMouseLeave: (e: any) => {
                // console.log(e, "leave")
            }
        });
        addEvent({ ...val, char: title[0] });
    }
    //添加K线底部图标覆盖物
    function addEvent(aim: any) {
        chart.createOverlay({
            name: "event",
            extendData: {
                data: aim,
                press: false,
                action: allTime[aim.timestamp].length > 1 ? "more" : aim.char
            },
            points: [
                {
                    timestamp: aim.timestamp,
                    value: aim.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log("点击addEvent==============》", e, aim);
                let extendData = e.overlay.extendData;
                let list = allTime[aim.timestamp];
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent && clickEvent(e, list, false);
                } else {
                    extendData.press = true;
                    clickEvent && clickEvent(e, list, true);
                }
            }
        });
    }
    async function loadData() {
        let aim = [];
        let url = URL_KLINE_DATA.replace("@", token);
        let param = { interval: interval };
        let res: any = await get(url, param).catch(err => {
            return {};
        });
        if (!res.data) {
            aim = [];
        } else {
            aim = res.data.map((item: any) => {
                return toChartData(item);
            });
        }
        sortList(aim, "timestamp", false);
        klineDataList = aim;
        chart.applyNewData(klineDataList);
    }
    //鏈上K线
    async function loadOnLine() {
        let param = {
            token: token,
            type: interval
        };
        let res: any = await get(URL_TOKEN_DATA, param);
        // console.warn("##############");
        let list = res.data ? res.data : [];
        if (list.length == 0) {
            loading.value = false;
        }
        let aim = list.map((i: any, idx: number) => {
            return i;
        });
        sortList(aim, "timestamp", false);
        klineDataList = aim;
        console.log("kline 图表数据 #######===============================》", klineDataList);
        flitterVolumePrecision(klineDataList);
        chart.applyNewData(klineDataList);
    }
    function resizeChart() {
        // chart.resize();
        setTimeout(() => {
            chart && chart.resize();
        }, 300);
        setTimeout(() => {
            chart && chart.executeAction("onZoom");
        }, 900);
        setTimeout(() => {
            chart && chart.executeAction("onScroll");
        }, 1200);
    }
    function addSignalBS(pot: any, onMouseEnter: Function, onMouseLeave: Function) {
        console.log("addSignalBS", pot);
        if (!pot.low) {
            const ary = chart.getDataList();
            const aim = ary.find((val: any, i: number) => {
                if (val.timestamp >= pot.timestamp) {
                    console.log(i);

                    console.log(val.timestamp - pot.timestamp, "当前 差值");
                    console.log(ary[i - 1].timestamp - pot.timestamp, "前一个 差值");

                    return true;
                }
                return false;
            });
            if (!aim) {
                return null;
            }
            pot.high = aim.high;
            pot.low = aim.low;
            pot.visible = true;
        }

        if (pot.action == "deposit") {
            //充值 红
            pot.color = "#F6475D";
        } else if (pot.action == "withdraw") {
            //提现 绿
            pot.color = "#0DCB81";
        }

        let direction = Number(pot.direction);
        return chart.createOverlay({
            name: "signal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            },
            onMouseEnter: onMouseEnter,
            onMouseLeave: onMouseLeave
        });
    }

    return {
        loading,
        curItem,
        move,
        initLitterChaet,
        moreList,
        tables,
        KLineType,
        initChart,
        flitterVolumePrecision,
        initDataChat,
        setChartData,
        resizeChart,
        changeChartStyle,
        getKlineData,
        addSignalBS,
        getOutInData,
        appendIndicator,
        addMark,
        maxUsdDay,
        setZoomAt
    };
};
